<template>
  <div>
    <!-- 查询与重置 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.metrics_name" prefix-icon="el-icon-search" style="width: 240px; margin-right: 10px" placeholder="请输入指标名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
      <el-button type="primary" plain style="margin-left: 10px" @click="handleAdd">添加指标</el-button>
    </div>

    <!-- 批量删除 -->
    <div class="card" style="margin-bottom: 5px" v-if="data.user.role === 'ADMIN'">
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="metrics_name" label="指标名称"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template v-slot="scope">
            <div class="action-buttons">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item label="指标名称">
          <el-input v-model="data.form.metrics_name" placeholder="请输入指标名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  metrics_name: null,
  ids: []
});

// 查询方法
const load = () => {
  request.get('/metrics/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      metrics_name: data.metrics_name
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    }
  });
};

// 添加指标
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
  data.dialogTitle = '添加指标';
};

// 编辑指标
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
  data.dialogTitle = '编辑指标';
};

// 添加请求
const add = () => {
  request.post('/metrics/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 更新请求
const update = () => {
  request.put('/metrics/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 保存方法
const save = () => {
  if (data.form.id) {
    update();
  } else {
    add();
  }
};

// 删除单个指标
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete('/metrics/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete("/metrics/delete/batch", { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 表格选中数据
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

// 重置
const reset = () => {
  data.metrics_name = null;
  load();
};

load();
</script>
<style>
.action-buttons {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  height: 100%; /* 确保容器填满表格单元格的高度 */
}

.action-buttons .el-button {
  margin: 2px 0; /* 为按钮之间添加一些间距 */
}
</style>